package com.xcc.opendd;

import android.os.Handler;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TakeManage implements Runnable {
    private static TakeManage takeManage;

    public static synchronized TakeManage getInstance() {
        if (takeManage == null) takeManage = new TakeManage();
        return takeManage;
    }

    private TakeManage() {
        init();
    }

    private void init() {
        modeList = new SqlHelp(AppLive.getInstance()).getList();
        //开启线程
        new Thread(this).start();
    }

    public synchronized void addTime(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HHmm");
        String format = dateFormat.format(date);
        int i = Integer.parseInt(format);
        SqlHelp sqlHelp = new SqlHelp(AppLive.getInstance());
        sqlHelp.insert(i);
        modeList = sqlHelp.getList();
    }

    public synchronized List<TimeMode> getList() {
        return modeList;
    }

    private synchronized List<TimeMode> getNewList() {
        return new ArrayList<>(getList());
    }

    public synchronized void delete(TimeMode mode) {
        SqlHelp sqlHelp = new SqlHelp(AppLive.getInstance());
        sqlHelp.delete(mode._id);
        modeList = sqlHelp.getList();
    }

    private void OpenDD() {
        AppLive appLive = AppLive.getInstance();
        appLive.wakeUpAndUnlock();
        boolean b = AppUtil.checkApplication(appLive, AppLive.DDAppPage);
        if (b) AppUtil.openAppByPackageName(appLive, AppLive.DDAppPage);
        appLive.releaseUnlock();
    }

    private List<TimeMode> modeList;

    public void run() {
        while (true) {
            if (takeManage == null) break;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HHmm");
            String format = simpleDateFormat.format(System.currentTimeMillis());
            int timeI = Integer.parseInt(format);
            List<TimeMode> modeList = getNewList();
            for (TimeMode mode : modeList) {
                if (mode.timeL == timeI) {
                    if (!mode.isOpen) {
                        Handler handler = AppLive.getInstance().handler;
                        handler.post(this::OpenDD);
                        mode.isOpen = true;
                    }
                    break;
                } else mode.isOpen = false;
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }
        }
    }
}
